// pages/album.js
import { getAlbumList, addAlbum, deleteAlbum } from '../../api/memo'


Page({

  /**
   * 页面的初始数据
   */
  data: {
    albumList: [],
    type: "",
    fileList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.getAlbum()

  },
  async getAlbum() {
    const res = await getAlbumList()
    this.setData({
      albumList: res.data
    })
  },

  onChange(event) {
    this.setData({
      type: event.detail
    })
  },

  async deleteAlbum(e) {
    const { id } = e.currentTarget.dataset
    const res = await deleteAlbum({ id })
    wx.showToast({ title: '删除成功', icon: 'none' });
    this.getAlbum()

  },

  goPhotoSet(e) {
    const { id, title } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/setting/photoSet?id=' + id + `&title=${title}`,
    })

  },

  afterRead(event) {
    const { file } = event.detail;

    const uploadTasks = this.uploadFilePromise(``, file.tempFilePath);
    Promise.all([uploadTasks])
      .then(data => {
        wx.showToast({ title: '上传成功', icon: 'none' });
        const newFileList = data.map(item => ({ url: item.fileID }));
        this.setData({ cloudPath: data, fileList: newFileList });
      })
      .catch(e => {
        wx.showToast({ title: '上传失败', icon: 'none' });
        console.log(e);
      });
  },

  uploadFilePromise(fileName, chooseResult) {
    const _name = `my-photo/${Math.random()}_${Date.now()}.${chooseResult.match(/\.(\w+)$/)[1]}`
    return wx.cloud.uploadFile({
      cloudPath: _name,
      filePath: chooseResult
    });
  },

  async submitAlbum() {
    if (!this.data.type) {
      return wx.showToast({ title: '请输入类型', icon: 'none' });
    }
    if (!this.data.fileList.length) {
      return wx.showToast({ title: '请选择图片', icon: 'none' });
    }
    const res = await addAlbum({
      title: this.data.type,
      imgUrl: this.data.fileList[0].url

    })

    if (res.errMsg === 'collection.add:ok') {
      wx.showToast({ title: '提交成功', icon: 'none' });
      this.getAlbum()
      this.setData({
        type: '',
        fileList: [],
      })
    }


  },

  deleteImg() {
    this.setData({
      fileList: [],
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})